package br.com.fogas.webservice.soap.impl;

import android.content.Context;
import br.com.fogas.utils.FogasUtility;
import br.com.fogas.utils.StringUtility;
import br.com.fogas.utils.exception.ParseXmlException;
import br.com.fogas.webservice.exception.ERaiseWebServiceException;
import br.com.fogas.webservice.exception.RespostaWebServiceException;
import br.com.fogas.webservice.exception.SemConexaoInternetException;
import br.com.fogas.webservice.exception.ServidorForaException;
import br.com.fogas.webservice.exception.TempoEsperaRespostaException;
import br.com.fogas.webservice.exception.WebServiceException;
import br.com.fogas.webservice.parser.BaseParser;
import br.com.fogas.webservice.parser.notafiscal.NotaFiscalResponse;
import br.com.fogas.webservice.soap.POCallbackSOAP;
import br.com.fogas.webservice.soap.TimeConnectionServer;

public class NotaFiscalSOAP extends POCallbackSOAP<NotaFiscalResponse>{
	
	public NotaFiscalSOAP(Context context, BaseParser parser) {
		super(context, parser);
	}

	@Override
	public String getInterface() {
		return "ZCI_SYNC_NOTA&interfaceNamespace=urn:sap-com:document:sap:rfc:functions";
	}
	
	@Override
	public TimeConnectionServer timeOutConnectionServer() {
		return new TimeConnectionServer(true, 10, 30);
	}

	@Override
	public String getXmlResponse() {
		final String regex = "<ns0:ZCI_SYNC_NOTA.Response[^>]*>(.*?)</ns0:ZCI_SYNC_NOTA.Response>";
		String responseXml = FogasUtility.string.getSubstringByRegex(regex, baseParser.getResponseXML());
		return StringUtility.normalizeSpace("<DATA>"+responseXml+ "</DATA>");
	}

	@Override
	public NotaFiscalResponse getResponse()
			throws SemConexaoInternetException, ParseXmlException,
			TempoEsperaRespostaException, ServidorForaException,
			RespostaWebServiceException, WebServiceException, ERaiseWebServiceException {
		super.sendRequest();
		
		NotaFiscalResponse response = (NotaFiscalResponse) FogasUtility.xml.unParseXML(NotaFiscalResponse.class, getXmlResponse());
		
		if(StringUtility.isNotEmpty(response.geteRaise())) {
			throw new ERaiseWebServiceException(response.geteRaise());
		}
		
		return response;
	}
}